package com.hyfrogx.modules.sys.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hyfrogx.common.base.BaseServiceImpl;
import com.hyfrogx.common.base.QueryForm;
import com.hyfrogx.common.exception.MyException;
import com.hyfrogx.common.utils.Constant;
import com.hyfrogx.common.utils.ShiroUtils;
import com.hyfrogx.modules.sys.form.file.FileSaveForm;
import com.hyfrogx.modules.sys.dao.SysFileDao;
import com.hyfrogx.modules.sys.entity.SysFileEntity;
import com.hyfrogx.modules.sys.service.SysFileService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * <p>
 * 文件 服务实现类
 * </p>
 *
 * @author wanglei
 * @date 2019-07-23 18:36:07
 */
@Service
public class SysFileServiceImpl extends BaseServiceImpl<SysFileDao, SysFileEntity> implements SysFileService {

	private final static String fileDirPath = "sys/file";

	@Override
	public String getIdKey() {
		return "id";
	}

	@Override
	public String getEntityName() {
		return "文件";
	}

	@Override
	public QueryWrapper<SysFileEntity> getSelectWrapper(QueryForm<SysFileEntity> form, boolean isOrder) {
		return null;
	}

	private File createFile(String id, String name) {
		//文件夹
		String extName = FileUtil.extName(name);
		return FileUtil.file(fileDirPath, StrUtil.format("{}.{}", id, extName));
	}

	@Override
	public File getBasePath() {
		return FileUtil.mkParentDirs(new File("temp").getAbsolutePath());
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public String uploadForm(MultipartFile file) {
		if (ObjectUtil.isNull(file)) {
			throw new MyException("文件上传失败");
		}
		FileSaveForm form = new FileSaveForm();
		form.setFileName(file.getOriginalFilename());
		form.setFileType(file.getContentType());
		form.setSize(file.getSize());
		SysFileEntity entity = this.saveFormToEntity(ShiroUtils.getUserId(), form);
		entity.setFileId(IdUtil.fastSimpleUUID());
		File filePath = createFile(entity.getFileId(), entity.getFileName());
		entity.setUploadName(filePath.getName());
		String basePathStr = FileUtil.getAbsolutePath(getBasePath());
		entity.setLocalUrl(FileUtil.subPath(basePathStr, filePath));
		if (this.save(entity)) {
			//写入文件
			try {
				FileUtil.writeBytes(file.getBytes(), filePath);
			} catch (IOException e) {
				throw new MyException("文件读取失败", e);
			}
			//todo 上传oss操作
		} else {
			throw new MyException("文件数据记录失败");
		}
		return entity.getFileId();
	}

	@Override
	public SysFileEntity getByFileId(String fileId) {
		return getByFileId(fileId, null);
	}

	public SysFileEntity getByFileId(String fileId, Integer status) {
		return this.getOne(
				new QueryWrapper<SysFileEntity>()
						.eq("file_id", fileId)
						.eq(ObjectUtil.isNotNull(status), "status", status)
		);
	}

	@Override
	public void downloadByFileId(HttpServletResponse response, String fileId) {
		SysFileEntity entity = this.getByFileId(fileId);
		if (ObjectUtil.isNotNull(entity)) {
			File file = FileUtil.file(getBasePath(), entity.getLocalUrl());
			ServletUtil.write(response, file);
		} else {
			throw new MyException(fileId + "文件不存在");
		}
	}

	@Override
	public SysFileEntity getUsedByFileId(String fileId) {
		return getByFileId(fileId, Constant.BasicStatus.TRUE.getValue());
	}
}
